/*
 * Copyright (C) 2011-2012 Andrew Wells
 *
 * Licensed under the GNU License, Version 3
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/copyleft/gpl.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Dungeons & Dragons Copyright (C) Wizards of the Coast. I do not claim
 * the right to any information used from their books or resources.
 */

package com.trace.wells.charactertracker;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class CharacterTracker extends Activity implements Serializable {

	private static final long serialVersionUID = 1L;
	/** Called when the activity is first created. */

	FileHelper fh = new FileHelper();

	public Boolean NEW_FILE;

	private String FILENAME = "data/data/com.trace.wells.charactertracker/characters.txt";

	public Button create_button;

	private ArrayList<String> characterInfo = new ArrayList<String>();

	private ArrayList<Character> characterList = new ArrayList<Character>();
	private static ListViewCustomAdapter adapter;
	private ListView itemListView;
	Hashtable<String, String> table = new Hashtable<String, String>();

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initMain();

		setupList();
	}

	@Override
	public void onResume() {
		super.onResume();

		characterInfo = fh.getStringCharacterList();
		String delimiter = "\\:";

		//If the file is empty
		if (characterInfo == null) {

		}
		for (String characterString : characterInfo) {
			String[] split = characterString.split(delimiter);

			//TODO: START HERE!!!!
		}
		adapter.setCharacterList(characterInfo);

		//characterList = fh.readCharacters(ConstantHelper.FILENAME);

		initMain();

		setupList();
	}

	public void setupList() {
		itemListView = (ListView) findViewById(R.id.list);
		adapter = new ListViewCustomAdapter(this, characterInfo);
		itemListView.setAdapter(adapter);

		itemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
				String characterString = (String) adapter.getItem(position);

				Intent i = new Intent(CharacterTracker.this, BattleScreen.class);

				//TODO: START HERE!!!
				//Open the correct character file based off the string object characterString

				String fileName = fh.convertCharacterInfoStringToFileName(characterString);

				try {
					Character character = fh.readInCharacter(fileName);
					Bundle extras = new Bundle();
					extras.putSerializable("character", character);

					fh.writeCharacters(ConstantHelper.FILENAME, characterList);

					i.putExtras(extras);
					startActivity(i);

				} catch (Exception e) {
					Log.e("CHAR", "Problem reading character from file: " + fileName);
				}
			}
		});

		itemListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				final int listItem = arg2;

				AlertDialog.Builder dialog = new AlertDialog.Builder(CharacterTracker.this);
				dialog.setTitle("Remove this character?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						String ri = (String) adapter.getItem(listItem);

						//						int ID = ri.getUniqueId();
						//
						//						dialog.cancel();
						//
						//						adapter.removeCharacter(ID);
						//
						//						adapter.notifyDataSetChanged();
						//
						//						fh.removeCharacterFile(ri.getFileIdentifier());

						//String[] characterInfo = adapter.getCharacterInfo(ID);
					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

				AlertDialog alert = dialog.create();
				alert.show();

				return true;
			}
		});
	}

	private void initMain() {
		create_button = (Button) findViewById(R.id.buttonCreate);

		create_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				fh.writeCharacters(ConstantHelper.FILENAME, characterList);
				Intent i = new Intent(CharacterTracker.this, CreateCharacter.class);
				startActivityForResult(i, ConstantHelper.REQUEST_CODE_CREATE_CHARACTER);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		setContentView(R.layout.main);
		try {
			if ((requestCode == ConstantHelper.REQUEST_CODE_CREATE_CHARACTER) && (resultCode == Activity.RESULT_OK)) {

				Bundle myResults = data.getExtras();

				Character character = (Character) myResults.get("character");

				//characterList.add(character);

				/////////////////////////////////////
				//TODO: Look below...
				/*
				 * This section of code should write the returned character:
				 * 	1. To its own file
				 *  2. Add it to the ArrayList<String> that has the other characterStrings in it.
				/*/
				/////////////////////////////////////

				//Adds the character to the ArrayList
				characterInfo.add(character.getCharacterArrayInformationString());

				//Writes the character to a new file
				FileHelper.writeSingleCharacter(ConstantHelper.FILE_DIRECTORY + character.getFileIdentifier(), character);

				//Adds the string character to characterArrayList.txt file to be used later.
				ArrayList<String> tempList = fh.getStringCharacterList();
				tempList.add(character.getCharacterArrayInformationString());
				fh.writeStringCharacters(ConstantHelper.CHARACTER_LIST_FILE, tempList);

				//NOT ANYMORE!!!
				//fh.writeCharacters(ConstantHelper.FILENAME, characterList);

				setupList();

				//adapter.notifyDataSetChanged();
			}
			if ((requestCode == ConstantHelper.REQUEST_CODE_BATTLE_SCREEN) && (resultCode == Activity.RESULT_OK)) {

				//TODO:
				/*
				 * This next line of code will require:
				 * 
				 * 	 the refactoring of the characterList variable. It should
				 * pull from the newly created characterString that holds all the information needed to display
				 * and choose the required files needed to move between characters in the selection screen.
				 * 
				 * 1. The re-doing of the setupList function. It should pull from the new string-based character info system
				 * 2.  The InitMain function that utilizes the characterList varaible as well.
				 * 
				 * 
				 */

				//characterList = fh.readCharacters(ConstantHelper.FILENAME);

				initMain();

				setupList();
			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Data was not read Successfully", Toast.LENGTH_LONG).show();
		}
	}
}